package com.mini.framework.web;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import com.mini.framework.core.AbstractApplicationContext;
import com.mini.framework.core.annotation.RequestMapping;
import com.mini.framework.core.util.View;
import com.mini.framework.web.handler.JsonViewHandler;
import com.mini.framework.web.handler.JspViewHandler;
import com.mini.framework.web.handler.XmlViewHandler;

public class WebApplicationContext extends  AbstractApplicationContext{
	
	private static final String VIEW_PATH = "view.path";
	
	private static final String DEFAULT_VIEW_PATH = "/WEB-INF/pages";
	
	public WebApplicationContext(){
		super();
	}


	@Override
	public void loadObject2Context(Class<?> c, Object o) {
		List<Method> methods = getRequestMappingMethod(c);
		for(Method m : methods){
			String url = m.getAnnotation(RequestMapping.class).value();
			String view = m.getAnnotation(RequestMapping.class).view();
			ViewHandler viewHandler = getViewHandler(view);
			RequestHandler handler = new RequestHandler(m,o,viewHandler);
			map.put(url, handler);
		}
	}
	
	private List<Method> getRequestMappingMethod(Class<?> c){
		List<Method> methodList = new ArrayList<Method>();
		Method[] methods = c.getDeclaredMethods();
		for(Method m : methods){
			if(m.isAnnotationPresent(RequestMapping.class)){
				methodList.add(m);
			}
		}
		return methodList;
	}
	
	private ViewHandler getViewHandler(String view){
		String viewPath = this.getConfigProperties().getProperty(VIEW_PATH);
		if(viewPath == null)
			viewPath = DEFAULT_VIEW_PATH;
		if(view.equals(View.JSP)){
			return new JspViewHandler(viewPath);
		}else if(view.equals(View.JSON)){
			return new JsonViewHandler();
		}else if(view.equals(View.XML)){
			return new XmlViewHandler();
		}
		return null;
	}
	
	
	
	
	

}
